package xxljob

import (
	"context"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/di"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/service/customer"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/xxl-job/xxl-job-executor-go"
	"sync"
)

var executor xxl.Executor
var once sync.Once

const (
	serverAddr  = "xxljob.server_addr"
	accessToken = "xxljob.access_token"
	clientName  = "xxljob.client_name"
	clientPort  = "xxljob.client_port"
)

func InitExecutor() {
	defer func() {
		if err := recover(); err != nil {
			stark.Logger.Errorf(context.Background(), "xxl-job initExecutor error: %v", err)
		}
	}()
	go initExecutor()
}

func initExecutor() {
	once.Do(func() {
		serverAddr := stark.Configer.(stark.ApolloConfigerIface).GetStringValue(serverAddr, "")
		accessToken := stark.Configer.(stark.ApolloConfigerIface).GetStringValue(accessToken, "")
		port := stark.Configer.(stark.ApolloConfigerIface).GetStringValue(clientPort, "9999")
		name := stark.Configer.(stark.ApolloConfigerIface).GetStringValue(clientName, "micro-gfyx-user-service")
		executor = xxl.NewExecutor(
			xxl.ServerAddr(serverAddr),
			xxl.AccessToken(accessToken),
			xxl.ExecutorPort(port),
			xxl.RegistryKey(name),
		)
		executor.Init()

		// 中间件
		// executor.Use()

		// 日志
		// executor.LogHandler()

		// 注册任务
		executor.RegTask("get_customer_group_total", getCustomerGroupTotal)
		err := executor.Run()
		if err != nil {
			stark.Logger.Errorf(context.Background(), "xxl-job Run error: %v", err)
		} else {
			stark.Logger.Infof(context.Background(), "xxl-job Run success")
		}
	})
}

func getCustomerGroupTotal(ctx context.Context, param *xxl.RunReq) (msg string) {
	inject := di.NewInject()
	err := inject.Invoke(func(customerService customer.CustomerGroupServiceIface) {
		err := customerService.SyncCustomerGroupTotal(ctx)
		if err != nil {
			stark.Logger.Errorf(ctx, "xxl-job getCustomerGroupTotal SyncCustomerGroupTotal error: %v", err)
		} else {
			stark.Logger.Info(ctx, "xxl-job getCustomerGroupTotal SyncCustomerGroupTotal success")
		}

	})
	if err != nil {
		stark.Logger.Errorf(ctx, "xxl-job getCustomerGroupTotal Invoke error: %v", err)
		return err.Error()
	}
	return "success"
}
